package com.tool4j.config;

import com.tool4j.common.Constants;
import com.tool4j.common.exception.*;
import com.tool4j.util.JsonUtil;
import com.tool4j.util.UserPermission;
import com.tool4j.util.http.IPUtil;
import com.tool4j.util.http.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.velocity.exception.ParseErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * WebFlux 全局异常处理器
 *
 * @author Deng.Weiping
 * @since 2023/7/24 15:04
 */
@ControllerAdvice
@Slf4j
@Order(-1) // 保证优先级高于其他处理器
public class GlobalExceptionResolver {

    @Autowired
    private IPUtil ipUtil;

    /**
     * 处理所有未捕获异常
     */
    @ExceptionHandler(Exception.class)
    public Mono<Void> handleException(Exception e, ServerWebExchange exchange) {
        ServerHttpRequest request = exchange.getRequest();
        String ip = ipUtil.getIp(request);
        String uri = request.getURI().toString();
        log.error("系统异常：ip={}, region={}, URI={}", ip, ipUtil.searchRegion(ip), uri, e);
        Result result;
        if (e instanceof BalanceException) {
            result = Result.error(Constants.RESPONSE_CODE_BALANCE, e.getMessage());
        } else if (e instanceof VipException) {
            result = Result.error(Constants.RESPONSE_CODE_VIP, e.getMessage());
        } else if (e instanceof VipPlusException) {
            result = Result.error(Constants.RESPONSE_CODE_VIP_PLUS, e.getMessage());
        } else if (e instanceof IllegalArgumentException) {
            result = Result.error(e.getMessage());
        } else if (e instanceof BizException) {
            result = Result.error(e.getMessage());
        } else if (e instanceof IllegalRequestException) {
            result = Result.error(Constants.RESPONSE_CODE_AUTH, "接口签名校验失败，请重试");
        } else if (e instanceof AuthException) {
            result = Result.error(Constants.UN_LOGIN, e.getMessage());
        } else if (e instanceof ParseErrorException) {
            result = Result.error(e.getMessage());
        } else {
            UserPermission.UserInfo userInfo = UserPermission.get(exchange);
            log.error("出错啦！：userId={}, ip={}, region={}", userInfo.getUserId(), userInfo.getIp(), userInfo.getRegion());
            result = Result.error("出错啦！请通过系统反馈告知管理员", e.getMessage());
        }
        var response = exchange.getResponse();
        response.setStatusCode(HttpStatus.OK); // 业务上返回 200
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
        response.getHeaders().set("Cache-Control", "no-cache, must-revalidate");
        byte[] bytes = JsonUtil.obj2JsonString(result).getBytes(StandardCharsets.UTF_8);
        var buffer = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(buffer));
    }
}